require 'find'

module Google
module Gears
module LocalServer

class Manifest
  LEADING_PERIOD = /\/\./
  
  attr_accessor :options, :entries

  def initialize(&b)
    @options = { # default options
      :manifest_version => 1
    }
    @entries = []

    # If you use the block option, return the output as a string
    if block_given?
      b.call(self)
      return self.to_s
    end
  end
  
  def with_options(new_options)
    options.merge!(new_options)
  end
  
  def add_entry(entry)
    entries << entry
  end
  
  def add_extra_info(info)
    entries.each do |e|
      if e[:url] == info[:to]
        e.merge!(info)
      end
    end
  end
  
  def find_entries(info)
    info[:in]   ||= '.'  # default to the current directory
    info[:root] ||= '' # default to relative
    
    Find.find(info[:in]) do |path|
      next if File.directory? path
      
      file = path.sub(Regexp.new("^#{info[:in]}/"), info[:root]) # setup the root for the path

      if info[:ignore]
        next if path.match info[:ignore]
      end
      
      if info[:include]
        if path.match info[:include]
          entries.push({ :url => file })
        end
        next
      end
      
      entries.push({ :url => file })
    end
  end
  
  def build_entries
    output_entries = []
    entries.each do |e|
      url = %Q{"url": "#{e[:url]}"}
      src = e[:src] ? %Q{, "src": "#{e[:src]}"} : ''
      redirect = e[:redirect] ? %Q{, "redirect": "#{e[:redirect]}"} : ''
      ignore_query = e[:ignore_query] ? %Q{, "ignoreQuery": #{e[:ignore_query]}} : ''
      
      output_entries << "\t{ #{url}#{src}#{redirect}#{ignore_query} }"
    end
    
    '"entries": [' + "\n" + output_entries.join(",\n") + ' ]'
  end
  
  def to_s
    manifest_version = %Q{"betaManifestVersion": #{options[:manifest_version]},}
    version = %Q{"version": "#{options[:version] || 'YouShouldPutInAVersion'}",} 
    redirect_url = options[:redirect_url] ? %Q{"redirectUrl": "#{options[:redirect_url]}",} : ''
    
    <<-OUTPUT;
{
  #{manifest_version}
  #{version}
  #{redirect_url}
  #{build_entries}
}
OUTPUT
  end
  
  # take a method and save the thing to the options hash
  def method_missing(method, value)
    method = method.to_s.sub(/=$/, '').to_sym # nuke the ending '='
    options[method] = value
  end
end

end;end;end

